package main

import (
	"fmt"
	"strconv"
	"strings"
)

const fitstCode = 19968
const endCode = 40959

/*
 *将输入进来的字符串转换成Unicode编码
 */
func ChineseToASCIIArr(input string) []int64 {
	inputQuoted := strconv.QuoteToASCII(input)
	inputQuoted = inputQuoted[1 : len(inputQuoted) - 1]
	inputQuoted = strings.ReplaceAll(inputQuoted, `\u`, " ")
	wordCodeStr := strings.Fields(inputQuoted)

	var wordCode []int64
	for _, v := range wordCodeStr {
		n, _ := strconv.ParseInt(v, 16, 64)
		if n < fitstCode || n > endCode {
			word := fmt.Sprintf("\"\\u%x\"", n)
			word , _ = strconv.Unquote(word)
			fmt.Println("请把\"" + word + "\"替换为常用汉字字符！")
			return nil
		}
		wordCode = append(wordCode, n)
	}

	// fmt.Println(wordCode)
	return wordCode
}

/*
 *移位加密
 */
func encryption(mCodeArr []int64, kCodeArr []int64) []int64 {
	if len(kCodeArr) > len(mCodeArr) {
		kCodeArr = kCodeArr[:len(mCodeArr)]
	}else if len(kCodeArr) < len(mCodeArr) {
		kLength := len(kCodeArr)
		for i := 0; len(kCodeArr) < len(mCodeArr); i++ {
			if i == kLength {
				i = 0
			}
			kCodeArr = append(kCodeArr, kCodeArr[i])
		}
	}

	var cCodeArr []int64
	for i := 0; i < len(mCodeArr); i++ {
		//需要移位的位数
		temp := kCodeArr[i] - fitstCode
		if temp > endCode - mCodeArr[i] {
			cCodeArr =  append(cCodeArr, fitstCode + (temp - (endCode - mCodeArr[i]) + 1))
		}else {
			cCodeArr = append(cCodeArr, mCodeArr[i] + temp)
		}
	}

	// fmt.Println(cCodeArr)
	return cCodeArr
}

func decrypt(cCodeArr []int64, kCodeArr []int64) []int64 {
	if len(kCodeArr) > len(cCodeArr) {
		kCodeArr = kCodeArr[:len(cCodeArr)]
	}else if len(kCodeArr) < len(cCodeArr) {
		kLength := len(kCodeArr)
		for i := 0; len(kCodeArr) < len(cCodeArr); i++ {
			if i == kLength {
				i = 0
			}
			kCodeArr = append(kCodeArr, kCodeArr[i])
		}
	}
	

	var mCodeArr []int64
	for i := 0; i < len(cCodeArr); i++ {
		temp := kCodeArr[i] - fitstCode
		if temp > cCodeArr[i] - fitstCode {
			mCodeArr = append(mCodeArr, endCode - (temp - (cCodeArr[i] - fitstCode)) - 1)
		}else {
			mCodeArr = append(mCodeArr, cCodeArr[i] - temp)
		}
	}
	// fmt.Println(mCodeArr)
	return mCodeArr
}

/*
 *将完成移位的字码转换成汉字
 */
func ASCIIToChinese(codeArr []int64) string {
	var chinese = ""
	for _, v := range codeArr {
		word := fmt.Sprintf("\"\\u%x\"", v)
		word , _ = strconv.Unquote(word)
		chinese += word
	}

	return chinese
}
